<template>
  <div class="club_content">
    <n-spin :show="loading">
      <div class="top_title">{{ t('club_page_club') }}</div>
      <n-flex class="top_box">
        <n-flex class="item_list button" v-for="(item, index) in listData"
          :style="{ 'background-image': `url(/img/club/new/bg${index + 1}.webp)` }" :key="index"
          @click="goToPage(item)">
          <n-flex align="flex-end" justify="center" class="item_list_l">
            <iconpark-icon :icon-id="item.icon" color="#fff" size="2.143em"></iconpark-icon>
          </n-flex>
          <n-flex justify="center" class="item_list_l">
            {{ t(item.label) }}
          </n-flex>
        </n-flex>
      </n-flex>

      <div class="bottom_box">
        <n-flex class="tab_list">
          <n-flex align="center" :class="`item_list button ${curTab === item.value && 'active'}`"
            v-for="(item, index) in tabData" :key="index" @click="clickTab(item.value)">
            <span :class="`icon ${item.icon}`"></span>
            <span class="txt"> {{ t(item.label) }} </span>
          </n-flex>
        </n-flex>
        <!-- 我加入的俱乐部 -->
        <n-flex v-show="curTab === 'joinClub'" class="join_club_box">
          <div class="nodata" v-if="!clubListData.length">
            <Imgt src="/img/wallet/nodata.webp" alt="nodata" />
            <div>{{ t('home_page_nomore_data') }}</div>
          </div>
          <n-flex align="center" class="item_list" v-for="(item, index) in clubListData" @click="goToNextPage(item)"
            :key="index">
            <div class="bg_txt">
              <div>JOIN THE</div>
              <div>CLUB</div>
            </div>
            <n-flex justify="center" class="item_list_l">
              <Imgt :src="returnClubLogo(item.club_logo, uploadUrl)" />
              <span v-if="item?.isMyself" class="c_box">{{ t('创建者') }}</span>
            </n-flex>
            <n-flex class="item_list_r">
              <div>{{ item.club_name }}</div>
              <div class="txt_dec">{{ item.club_intro }}</div>
            </n-flex>
          </n-flex>
        </n-flex>
        <!-- 我加入的牌局 -->
        <n-flex v-show="curTab === 'joinPlay'" class="join_club_box">
          <div class="nodata" v-if="!gameListData.length">
            <Imgt src="/img/wallet/nodata.webp" alt="nodata" />
            <div>{{ t('home_page_nomore_data') }}</div>
          </div>
          <n-flex align="center" class="item_list" v-for="(item, index) in gameListData" :key="index">
            <div class="bg_txt">
              <div>JOINED</div>
              <div>GAME</div>
            </div>
            <n-flex justify="center" class="item_list_l">
              <Imgt :src="returnClubLogo(item.game_logo, uploadUrl)" />
              <!--            <span class="c_box">{{ t('创建者') }}</span>-->
            </n-flex>
            <n-flex class="item_list_r">
              <div>{{ item.desk_name }}</div>
              <n-flex class="txt_dec">
                <n-flex class="item_bb">
                  <span class="icon">
                    <iconpark-icon size="1.042rem" name="paihiconss01"></iconpark-icon>
                  </span>
                  <span class="item_r_txt txt_ellipsis">{{ `${item.current_players}/${item.max_players}` }}</span>
                </n-flex>
                <n-flex class="item_bb">
                  <span class="icon">
                    <Imgt :src="`/img/club/new/bankIcon.webp`" />
                  </span>
                  <span class="item_r_txt txt_ellipsis">{{ item.need_chip }}$</span>
                </n-flex>
                <n-flex class="item_bb">
                  <span class="icon">
                    <Imgt :src="`/img/club/new/monIcon.webp`" />
                  </span>
                  <span class="item_r_txt txt_ellipsis">{{ `${item.min_money}/${item.max_money}` }}</span>
                </n-flex>
              </n-flex>
            </n-flex>
          </n-flex>
        </n-flex>

      </div>
    </n-spin>
  </div>

  <!-- 加入俱乐部弹窗 -->
  <ModalDialog v-model:visible="showJoinModal" secClass="form_card_sec" title="club_page_jrjlb">
    <template #content>
      <div class="form_body">
        <n-form>
          <n-form-item :label="t('club_page_clubId')">
            <n-input v-model:value="joinParams.id" :placeholder="t('club_page_qsr')" clearable />
          </n-form-item>
        </n-form>
        <n-flex class="form_footer" justify="space-between">
          <button class="c_join_btn button_color" :disabled="(!canJoin || !joinParams.id)" @click="onSubmit"
            style="width: 100%"> {{ t('搜素') }}
          </button>
        </n-flex>
      </div>
    </template>
  </ModalDialog>

  <!-- 加入牌局弹窗 -->
  <ModalDialog v-model:visible="showCardModal" secClass="form_card_sec" title="club_page_jrpj">
    <template #content>
      <div class="form_body">
        <n-form>
          <n-form-item :label="t('搜索输入牌局ID')">
            <n-input v-model:value="joinParams.id" :placeholder="t('club_page_qsr')" clearable />
          </n-form-item>
        </n-form>
        <n-flex class="form_footer" justify="space-between">
          <button class="c_join_btn button_color" :disabled="(!canJoin || !joinParams.id)" @click="onPlaySubmit"
            style="width: 100%"> {{ t('搜素') }}
          </button>
        </n-flex>
      </div>
    </template>
  </ModalDialog>

  <!-- 创建俱乐部弹窗 -->
  <ModalDialog v-model:visible="showCreateModal" secClass="form_card_sec" title="club_page_cjjlb">
    <template #content>
      <div class="form_body">
        <n-form>
          <n-flex align="center" class="upload_img">
            <span>{{ t('上传图片') }}:</span>
            <n-upload :max="1" @before-upload="beforeUpload" accept=".jpg,.jpeg,.png,.gif,.webp">
              <n-button>上传</n-button>
            </n-upload>
          </n-flex>
          <n-form-item :label="`${t('club_page_jlbmc')}:`">
            <n-input type="textarea" :rows="2" v-model:value="createParams.name" :placeholder="t('club_page_qsr')" :bordered="false"
              clearable />
          </n-form-item>
          <n-form-item :label="`${t('club_page_jlbjj')}:`">
            <n-input type="textarea" :rows="2" v-model:value="createParams.dec" :placeholder="t('club_page_qsr')" :bordered="false"/>
          </n-form-item>
        </n-form>
        <n-flex class="form_footer" justify="space-between">
          <a @click="onCloseCreate"> {{ t('home_page_cancel') }} </a>
          <a class="c_join_btn button_color" @click="onSubmitCreate"> {{ t('club_page_ljcj')
            }} </a>
        </n-flex>
      </div>
    </template>
  </ModalDialog>

  <!-- 快速开始弹窗 -->
  <ModalDialog v-model:visible="showQuickModal" secClass="form_card_sec" title="快速开始">
    <template #content>
      <div class="form_body form_body_quick">
        <n-flex class="quick_box">
          <div class="ks_list button">
            <Imgt :src="`/img/club/new/game1.webp`" />
            <div class="txt_ellipsis">游戏名称</div>
          </div>
          <div class="ks_list button">
            <Imgt :src="`/img/club/new/game2.webp`" />
            <div class="txt_ellipsis">游戏名称</div>
          </div>
          <div class="ks_list button">
            <Imgt :src="`/img/club/new/game3.webp`" />
            <div class="txt_ellipsis">游戏名称</div>
          </div>
          <div class="ks_list button">
            <Imgt :src="`/img/club/new/game4.webp`" />
            <div class="txt_ellipsis">游戏名称</div>
          </div>
          <div class="ks_list button">
            <Imgt :src="`/img/club/new/game5.webp`" />
            <div class="txt_ellipsis">游戏名称</div>
          </div>
        </n-flex>
      </div>
    </template>
  </ModalDialog>

</template>

<script setup lang='ts' name="clubInfo">
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import Imgt from '@/components/Imgt.vue';
import { NetPacket } from '@/netBase/NetPacket';
import H5Websocket from "@/net/Net1";
import { MessageEvent2 } from '@/net/MessageEvent2.ts';
import { NetMsgType } from '@/netBase/NetMsgType.ts';
import { Message } from '@/utils/discreteApi.ts';
import { returnClubLogo } from '@/utils/publicMethods.ts';
import { User } from '@/store/user.ts';
import pinia from '@/store';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
// import { useRoute } from 'vue-router';
import ModalDialog from '@/components/ModalDialog.vue';
import { Page } from '@/store/page.ts';

const UserStore = User(pinia);
const { roleInfo } = storeToRefs(UserStore);
const { club_list_all } = storeToRefs(Page(pinia));
const { t } = useI18n();
// const route = useRoute();
const router = useRouter();
const uploadUrl = ref();
const loading = ref(false);
const showModal = ref(false);
const showJoinModal = ref(false);
const showCreateModal = ref(false);
const showCardModal = ref(false);
const showQuickModal = ref(false);
const canJoin = ref(true); // 是否可以加入俱乐部
const curTitle = ref('俱乐部');
const curTab = ref('joinClub'); // joinClub, joinPlay

const tabData = ref([
  { label: '我加入的俱乐部', value: 'joinClub', icon: 'icon_club' },
  { label: '我加入的牌局', value: 'joinPlay', icon: 'icon_game' },
]);
const listData = ref([
  { label: 'club_page_cjjlb', value: 'create', icon: 'jlbiconcjjub' },
  { label: 'club_page_jrjlb', value: 'join', icon: 'jlbiconjhqs02' },
  { label: 'club_page_jrpj', value: 'joinPlay', icon: 'jlbiconjhqs03' },
  { label: '快速开始', value: 'start', icon: 'jlbiconjhqs04' },
]);
// 我加入的牌局
const gameListData: any = ref(
  [
    // {
    //   name: '经典德州-1860',
    //   type: '【美元桌】',
    //   minBet: 25,
    //   icon: 'avatar',
    //   rate: '0.25/0.50',
    //   count: '3/8',
    // },
    // {
    //   name: '经典德州-1860',
    //   type: '【美元桌】',
    //   minBet: 25,
    //   icon: 'avatar',
    //   rate: '0.25/0.50',
    //   count: '3/8',
    // },
    // {
    //   name: '经典德州-1860',
    //   type: '【美元桌】',
    //   minBet: 25,
    //   icon: 'avatar',
    //   rate: '0.25/0.50',
    //   count: '3/8',
    // },
    // {
    //   name: '经典德州-1860',
    //   type: '【美元桌】',
    //   minBet: 25,
    //   icon: 'avatar',
    //   rate: '0.25/0.50',
    //   count: '3/8',
    // },
    // {
    //   name: '经典德州-1860',
    //   type: '【美元桌】',
    //   minBet: 25,
    //   icon: 'avatar',
    //   rate: '0.25/0.50',
    //   count: '3/8',
    // },
  ],
);
// 我加入的俱乐部
const clubListData: any = ref(
  [
    // {
    //   create: 'fsf898',
    //   name: '俱乐部-分部名称',
    //   id: 23233,
    //   dec: '俱乐部简介俱乐',
    // },
    // {
    //   create: 'fsf898',
    //   name: '俱乐部-分部名称',
    //   id: 23233,
    //   dec: '俱乐部简介俱乐部简介俱乐部简介俱乐部简介简俱乐部简介俱乐部简介俱乐部简',
    // },
    // {
    //   create: 'fsf898',
    //   name: '俱乐部-分部名称',
    //   id: 23233,
    //   dec: '俱乐部简介俱乐部简介俱乐部简介俱乐部简介简俱乐部简介俱乐部简介俱乐部简',
    // },
    // {
    //   create: 'fsf898',
    //   name: '俱乐部-分部名称',
    //   id: 23233,
    //   dec: '俱乐部简介俱乐部简介俱乐部简介俱乐部简介简俱乐部简介俱乐部简介俱乐部简',
    // },
  ],
);
// 加入俱乐部表单提交
const joinParams = ref({
  id: '',
});
// 创建俱乐部表单提交
const createParams = ref({
  name: '',
  imgUrl: '',
  dec: '',
});
// 获取图片上传的路径
const getImgUrl = () => {
  loading.value = true
  const req = NetPacket.req_resource_upload_url();
  H5Websocket.sendMessageHandler(req);
}
const getUploadUrl = async (res: any) => {
  setTimeout(() => {
    loading.value = false
  }, 500)
  const resData = JSON.parse(res?.upload_url || '');
  uploadUrl.value = resData.pc_api_url + '/';
  localStorage.setItem("upload_Url_Info", uploadUrl.value);
  await Page(pinia).setUploadUrl(uploadUrl.value);
}
// 上传图片
const beforeUpload = (data: any) => {
  const file = data.file.file;
  if (file && file.size > 1024 * 1024 * 2) { // 2MB限制
    Message.error('文件大小不能超过2MB！');
    return;
  }
  const formData = new FormData();
  formData.append('image', file);
  formData.append('device_id', `${roleInfo.value.id}`);
  fetch(`${uploadUrl.value}api/upload/img`, {
    method: 'POST',
    body: formData,
  })
    .then(response => response.json()).then(response => {
      if (response.status == 200 || response.status == 'success') {
        const urlImg = response.data.path;
        createParams.value.imgUrl = urlImg
        Message.success(response.message);
        console.log('&&&&&', urlImg);
      } else {
        Message.error(response.message);
      }
    });
};

const goToPage = (item: any) => {
  if (item.value === 'create') {
    showCreateAc();
  } else if (['join'].includes(item.value)) {
    showJoinAc();
  } else if (item.value === 'joinPlay') {
    showPlayAc();
  } else { // 快速开始
    getQuickList();
  }
};
const goToNextPage = (item: any) => {
  router.push(`/clubNext?club_id=${item.club_id}`)
}
const showJoinAc = () => {
  joinParams.value = { id: '' };
  showJoinModal.value = true;
};
const showCreateAc = () => {
  createParams.value = {
    name: '',
    imgUrl: '',
    dec: '',
  };
  showCreateModal.value = true;
};
const showPlayAc = () => {
  joinParams.value = { id: '' };
  showCardModal.value = true;
};
const openModal = () => {
  showModal.value = !showModal.value;
};

const clickTab = (e: any) => {
  curTab.value = e;
  curTitle.value = e === 'joinClub' ? t('club_page_club') : t('club_page_ycj');
};

// 加入俱乐部提交
const onSubmit = () => {
  console.log('----------', joinParams);
  const id = joinParams.value.id.trim();
  const req: any = NetPacket.req_join_club();
  req.club_id = id;
  H5Websocket.sendMessageHandler(req);
};
// 监听加入俱乐部
const joinClubHandle = (res: any) => {
  const tipStr: any = {
    0: '成功加入申请',
    1: '俱乐部不存在',
    2: '你已经申请加入，待审批',
    3: '不能重复加入',
  };
  showJoinModal.value = false;
  if (res.result === 0) {
    getClubList();
    Message.success(t(tipStr[res.result]));
  } else {
    Message.error(t(tipStr[res.result]));
  }
};
// 加入牌桌
const onPlaySubmit = () => {
  console.log('----------', joinParams);
  const id = joinParams.value.id.trim();
  const req: any = NetPacket.req_join_desk();
  req.desk_id = id;
  H5Websocket.sendMessageHandler(req);
};
// 监听加入牌桌，0加入成功；1 牌局不存在；2 牌局已停止；3 非代理创建的牌局；4 已满桌；5 不能重复加入牌局
const joinPlayHandle = (res: any) => {
  const tipStr: any = {
    0: '成功加入申请',
    1: '牌桌不存在',
    2: '牌局已停止',
    3: '非代理创建的牌局',
    4: '已满桌',
    5: '不能重复加入牌局',
  };
  showCardModal.value = false;
  if (res.result === 0) {
    Message.success(t(tipStr[res.result]));
  } else {
    Message.error(t(tipStr[res.result]));
  }
};

// 搜索俱乐部, 获取俱乐部信息，加入俱乐部前需要查询是否存在
// const searchClub = () => {
//   console.log('搜索---');
//   const id = joinParams.value.id.trim();
//   if (!id) {
//     return Message.error(t('请输入俱乐部ID'));
//   }
//   const req = NetPacket.req_get_club_info();
//   req.club_id = id;
//   H5Websocket.sendMessageHandler(req);
// };
// 监听获取俱乐部信息
const getClubInfoHandle = (res: any) => {
  if (res.club_id) {
    canJoin.value = true;
  } else {
    Message.error(t('俱乐部不存在'));
  }
};
// 关闭创建俱乐部弹窗
const onCloseCreate = () => {
  showCreateModal.value = false;
};
// 创建俱乐部提交
const onSubmitCreate = () => {
  console.log('----------', createParams);
  if (!createParams.value.name) {
    return Message.error(t('俱乐部名称不能为空'));
  }
  if (!createParams.value.dec) {
    return Message.error(t('俱乐部简介不能为空'));
  }
  const req: any = NetPacket.req_create_club();
  req.club_name = createParams.value.name;
  req.club_introduction = createParams.value.dec;
  req.club_logo = createParams.value.imgUrl || 0; // logo
  H5Websocket.sendMessageHandler(req);
};
// 监听创建俱乐部返回
const createClubHandle = (res: any) => {
  const tipStr: any = {
    0: '创建成功',
    1: '抽水比例配置不对',
    2: '俱乐部名称已经存在',
    3: '代理等级不正确',
    4: '俱乐部数量达到上限',
    5: '名称或简介长度不符合要求',
  };
  console.log('创建俱乐部==', res);
  if (res.result === 0) {
    Message.success(t(tipStr[res.result]));
    showCreateModal.value = false;
    getClubList();
  } else {
    Message.error(t(tipStr[res.result]));
  }
};
// 获取俱乐部列表
const getClubList = () => {
  const req = NetPacket.req_get_club_list();
  H5Websocket.sendMessageHandler(req);
};
// 监听俱乐部列表返回, res.created_club_list 创建的俱乐部列表， res.joined_club_list 加入的俱乐部列表
const getClubListHandle = () => {
  if (Object.keys(club_list_all.value).length) {
    clubListData.value = [...club_list_all.value.created_club_list, ...club_list_all.value.joined_club_list];
    console.log('******俱乐部列表', clubListData.value)
  }
};
// 我加入的牌局列表
const getMyDeskList = () => {
  const req = NetPacket.req_get_joined_dest_list();
  req.page = 1;
  H5Websocket.sendMessageHandler(req);
}
// 监听加入牌局列表
const getPlayHandle = (res: any) => {
  console.log('加入牌局列表==', res);
  gameListData.value = res.desk_list
};

// 获取快速开始游戏列表
const getQuickList = () => {
  const req = NetPacket.req_quick_start_game();
  H5Websocket.sendMessageHandler(req);
}
const getQuickStartHandle = (res: any) => {
  showQuickModal.value = true;
  console.log('33###', res)
}
watch(
  () => club_list_all.value,
  (n) => {
    if (n) {
      getClubListHandle()
    }
  }
);

onUnmounted(() => {
  // 取消监听
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_resource_upload_url, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_create_club, null);
  // MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_club_list, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_club_info, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_join_club, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_join_desk, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_get_joined_dest_list, null);
  MessageEvent2.removeMsgEvent(NetMsgType.msgType.msg_notify_quick_start_game, null);
});
onMounted(() => {
  getClubListHandle();
  getImgUrl();
  getClubList();
  getMyDeskList();

  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_resource_upload_url, getUploadUrl);

  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_create_club, createClubHandle);
  // MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_club_list, getClubListHandle);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_club_info, getClubInfoHandle);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_join_club, joinClubHandle);
  // 加入牌桌
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_join_desk, joinPlayHandle);
  // 我加入的牌局列表
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_get_joined_dest_list, getPlayHandle);
  MessageEvent2.addMsgEvent(NetMsgType.msgType.msg_notify_quick_start_game, getQuickStartHandle);
});

defineExpose({
  openModal,
});

</script>

<style lang='less' scoped>
@import '@/assets/club.less';

.top_box {
  gap: 40px !important;
}
</style>
